package com.adan.content.service.impl;

import com.adan.base.execption.CommonError;
import com.adan.base.execption.XcPlusException;
import com.adan.content.config.MultipartSupportConfig;
import com.adan.content.feignclient.MediaServiceClient;
import com.adan.content.mapper.CoursePublishMapper;
import com.adan.content.model.dto.CourseBaseInfoDto;
import com.adan.content.model.dto.CoursePreviewDto;
import com.adan.content.model.dto.TeachplanDto;
import com.adan.content.model.po.CourseBase;
import com.adan.content.model.po.CourseMarket;
import com.adan.content.model.po.CoursePublish;
import com.adan.content.model.po.CoursePublishPre;
import com.adan.content.service.*;
import com.adan.message.model.po.MqMessage;
import com.adan.message.service.MqMessageService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author adan
 */
@Slf4j
@Service
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish> implements CoursePublishService {

    @Resource
    CourseBaseService courseBaseService;
    @Resource
    TeachplanService teachplanService;
    @Resource
    CourseMarketService courseMarketService;
    @Resource
    CoursePublishPreService coursePublishPreService;
    @Resource
    MqMessageService mqMessageService;

    @Resource
    MediaServiceClient mediaServiceClient;


    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        // 课程基本信息、营销信息
        CourseBaseInfoDto courseBaseInfoDto = courseBaseService.queryCourseBaseById(courseId);
        // 课程计划信息
        List<TeachplanDto> teachplanDtos = teachplanService.queryTeachPlanTreeNode(courseId);
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfoDto);
        coursePreviewDto.setTeachplans(teachplanDtos);
        return coursePreviewDto;
    }

    @Override
    @Transactional
    public void commitAudit(Long companyId, Long courseId) {
        // 1、查询课程基本信息、课程营销信息、课程计划信息等课程相关信息，整合为课程预发布信息。
        CourseBaseInfoDto courseBaseInfo = courseBaseService.queryCourseBaseById(courseId);
        if (courseBaseInfo == null) {
            XcPlusException.cast("课程找不到");
        }
        // 本机构只允许提交本机构的课程
        if (!companyId.equals(courseBaseInfo.getCompanyId())) {
            XcPlusException.cast("本机构只允许提交本机构的课程");
        }
        // 审核状态
        String auditStatus = courseBaseInfo.getAuditStatus();
        // 如果课程的审核状态为已提交则不允许提交
        if (auditStatus.equals("202003")) {
            XcPlusException.cast("课程已提交请等待审核");
        }
        // 课程的图片、计划信息没有填写也不允许提交
        String pic = courseBaseInfo.getPic();
        if (StringUtils.isEmpty(pic)) {
            XcPlusException.cast("请求上传课程图片");
        }

        // 查询课程计划
        List<TeachplanDto> teachplanDtoList = teachplanService.queryTeachPlanTreeNode(courseId);
        // 1.4 没有添加课程计划，不允许提交审核
        if (teachplanDtoList.isEmpty()) {
            XcPlusException.cast("没有添加课程计划，不允许提交审核");
        }
        // 将查询到的课程基本信息、营销信息、计划等信息插入到课程预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfo, coursePublishPre);
        // 设置机构id
        coursePublishPre.setCompanyId(companyId);
        // 营销信息
        CourseMarket courseMarket = courseMarketService.getById(courseId);
        coursePublishPre.setMarket(JSON.toJSONString(courseMarket));
        // 计划信息
        coursePublishPre.setTeachplan(JSON.toJSONString(teachplanDtoList));
        // 提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());
        // 设置预发布记录状态为已提交
        coursePublishPre.setStatus("202003");
        coursePublishPreService.saveOrUpdate(coursePublishPre);

        // 更新课程基本信息表的审核状态为已提交
        CourseBase courseBase = courseBaseService.getById(courseId);
        // 审核状态为已提交
        courseBase.setAuditStatus("202003");
        courseBaseService.updateById(courseBase);
    }

    /**
     * 课程发布
     *
     * @param companyId 机构id
     * @param courseId  课程id
     */
    @Override
    @Transactional
    public void coursepublish(Long companyId, Long courseId) {
        // 约束校验
        // 查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreService.getById(courseId);
        if (coursePublishPre == null) {
            XcPlusException.cast("请先提交课程审核，审核通过才可以发布");
        }
        // 本机构只允许提交本机构的课程
        if (!coursePublishPre.getCompanyId().equals(companyId)) {
            XcPlusException.cast("不允许提交其它机构的课程。");
        }
        // 课程审核状态
        String auditStatus = coursePublishPre.getStatus();
        // 审核通过方可发布
        if (!"202004".equals(auditStatus)) {
            XcPlusException.cast("操作失败，课程审核通过方可发布。");
        }
        // 保存课程发布信息
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        coursePublish.setStatus("203002");
        this.saveOrUpdate(coursePublish);
        // 更新课程基本表的发布状态
        CourseBase courseBase = new CourseBase();
        courseBase.setStatus("203002");
        courseBase.setId(courseId);
        courseBaseService.updateById(courseBase);
        // 保存消息表
        saveCoursePublishMessage(courseId);

        // 删除课程预发布表对应记录
        boolean remove = coursePublishPreService.removeById(courseId);
        if (!remove) {
            XcPlusException.cast("/删除课程预发布表失败");
        }
    }

    /**
     * 生成课程静态页面
     *
     * @param courseId 课程id
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {
        File htmlFile = null;
        try {
            // 配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            // 加载模板
            // 选指定模板路径,classpath下templates下
            // 得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            // 设置模板加载目录
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            // 设置字符编码
            configuration.setDefaultEncoding("utf-8");

            // 指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            // 准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            // 静态化
            // 将模板转成html字符串
            // 参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//            System.out.println(content);
            // 将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            // 创建静态化文件
            htmlFile = File.createTempFile("course", ".html");
            log.debug("课程静态化，生成静态文件:{}", htmlFile.getAbsolutePath());
            // 输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}",e.toString());
            XcPlusException.cast("课程静态化异常");
        }
        return htmlFile;
    }

    /**
     * 上传课程静态页面
     *
     * @param courseId 课程id
     * @param file     静态化文件
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String course = mediaServiceClient.upload(multipartFile, "course", courseId + ".html");
        if(course == null){
            XcPlusException.cast("远程调用媒资服务上传文件失败");
        }
        file.delete();
    }

    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        CoursePublish coursePublish = this.getById(courseId);
        return coursePublish ;
    }

    /**
     * 向消息表插记录
     *
     * @param courseId 课程id
     */
    private void saveCoursePublishMessage(Long courseId) {
        MqMessage message = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if (message == null) {
            XcPlusException.cast(CommonError.QUERY_NULL);
        }
    }


}
